package com.xjh.t.controller;


import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.sun.corba.se.impl.orbutil.ObjectUtility;
import com.xjh.t.common.*;
import com.xjh.t.domain.AreaInfo;
import com.xjh.t.domain.GroupInfo;
import com.xjh.t.domain.OrderInfo;
import com.xjh.t.domain.UserInfo;
import com.xjh.t.mapper.OrderInfoMapper;
import com.xjh.t.service.IAreaInfoService;
import com.xjh.t.service.IGroupInfoService;
import com.xjh.t.service.IOrderInfoService;
import com.xjh.t.service.IUserInfoService;
import com.xjh.t.vo.GroupInfoVo;
import com.xjh.t.vo.OrderInfoVo;
import com.xjh.t.vo.OrderStaticVo;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.util.ObjectUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2020-03-12
 */
@RestController
@RequestMapping("/orderInfo")
public class OrderQueryController {

    @Autowired
    private IGroupInfoService groupInfoService;
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IAreaInfoService areaInfoService;

    @Autowired
    private IOrderInfoService orderInfoService;

    private MybatisSqlSessionFactoryBean sqlSessionFactoryBean;

    private  SqlSession sqlsession;

    private Map<String,Float> lastDayOrderAmount = new HashMap<>();
    private Map<String,Integer> lastDayOrderNum = new HashMap<>();

    private Map<String,Float> lastMonthOrderAmount = new HashMap<>();
    private Map<String,Integer> lastMonthOrderNum = new HashMap<>();

   // private OrderInfoMapper orderInfoMapper;

    @RequestMapping("getOrderList")
    public DataGridView getOrderList(OrderInfoVo vo) throws Exception {
        IPage<OrderInfo> page = new Page<>(vo.getPage(),vo.getLimit());
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(vo.getOrText()),"or_text",vo.getOrText());

        queryWrapper.eq(vo.getOrStatus() != null && vo.getOrStatus() < 2,"or_status",vo.getOrStatus());

        queryWrapper.eq("or_type",0);
        // queryWrapper.eq("or_id","18014398509481985");

        if(vo.getStartTime() == null)
        {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            String datestr = simpleDateFormat.format(new Date());
            vo.setStartTime(sdf.parse(datestr + " 00:00:00"));
            vo.setEndTime(sdf.parse(datestr + " 23:59:59"));

        }
        queryWrapper.ge(vo.getStartTime() != null,"or_date",vo.getStartTime());
        queryWrapper.le(vo.getEndTime() != null,"or_date",vo.getEndTime());

        queryWrapper.orderByDesc("or_date");

//        String url1 = "jdbc:mysql://127.0.0.1:3306/scfy?serverTimezone=UTC&useUnicode=true&useSSL=false&characterEncoding=utf8";
//
//        openSqlSession(url1);
//        if(orderInfoMapper == null)
//            orderInfoMapper = sqlsession.getMapper(OrderInfoMapper.class);

        this.orderInfoService.page(page,queryWrapper);
      //  System.out.println(page.getTotal());
        //this.orderInfoService.page(page,queryWrapper);

        List<UserInfo> userInfos = this.userInfoService.list();
        Map<Integer,String> userAccount = userInfos.stream().collect(Collectors.toMap(UserInfo::getUrId, UserInfo::getUrPhonenumber));

        List<GroupInfo> groupInfos = this.groupInfoService.list();
        Map<Long,String> groupMap = groupInfos.stream().collect(Collectors.toMap(GroupInfo::getGpId, GroupInfo::getGpName));

        List<OrderInfo> list = page.getRecords();
        List<OrderInfoVo> result = new ArrayList<>();
        for(OrderInfo g1:list) {

            OrderInfoVo orderInfoVo = new OrderInfoVo();
            BeanUtils.copyProperties(g1, orderInfoVo);

            orderInfoVo.parseOrderInfo();
            orderInfoVo.setOrderAccount(userAccount.get(orderInfoVo.getUrId()));
            orderInfoVo.setOrderCompany(groupMap.get(orderInfoVo.getGpId().longValue()));
            result.add(orderInfoVo);

        }
        queryWrapper.select("or_amount");
        List<OrderInfo> orderInfos = this.orderInfoService.list(queryWrapper);
        //sqlsession.close();

        float amount = 0;

        for(OrderInfo orderInfo:orderInfos)
        {
            try {
                amount += orderInfo.getOrAmount();
            }
            catch (Exception e)
            {
                //System.out.println(orderInfo.getOrId());
            }
        }

        return new DataGridView(page.getTotal(),result,amount);
    }


    @RequestMapping("getDayOrderChart")
    public ChartData getDayOrderChart() throws Exception {


            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


            Integer i=10;
            Date starttime;
            Date endtime;

            List<Float> amountList = new ArrayList();
            List<String> timelist = new ArrayList();
            List<Integer> orderNumList = new ArrayList();

            for (; i >= 0; i--) {


                QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();

                Date date = new Date();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);

                calendar.add(Calendar.DAY_OF_MONTH, -i);
                String datestr = simpleDateFormat.format(calendar.getTime());

                if(lastDayOrderAmount.get(datestr) != null)
                {
                    amountList.add(lastDayOrderAmount.get(datestr));
                    orderNumList.add(lastDayOrderNum.get(datestr));
                    timelist.add(calendar.get(Calendar.DATE)+"");

                }
                else {
                    starttime = sdf.parse(datestr + " 00:00:00");
                    endtime = sdf.parse(datestr + " 23:59:59");

                    timelist.add(calendar.get(Calendar.DATE)+"");

                    queryWrapper.ge(starttime != null, "or_date", starttime);
                    queryWrapper.le(endtime != null, "or_date", endtime);
                    queryWrapper.eq("or_status",1);

                    //System.out.println("查询日期：" + datestr);
                    List<OrderInfo> orderInfos = this.orderInfoService.list(queryWrapper);
                    float amount = 0;


                    for (OrderInfo orderInfo : orderInfos) {
                        try {
                            amount += orderInfo.getOrAmount();
                        } catch (Exception e) {
                            //System.out.println(orderInfo.getOrId());
                        }
                    }
                    amountList.add(amount);
                    orderNumList.add(orderInfos.size());
                    if(i !=0) {
                        lastDayOrderAmount.put(datestr, amount);
                        lastDayOrderNum.put(datestr,orderInfos.size());
                    }
                }

            }



            return new ChartData(amountList.size(),timelist,amountList,orderNumList);
    }

    @RequestMapping("getMonthOrderChart")
    public ChartData getMonthOrderChart() throws Exception {



        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


        Integer i=9;
        Date starttime;
        Date endtime;

        List<Float> amountList = new ArrayList();
        List<String> timelist = new ArrayList();
        List<Integer> orderNumList = new ArrayList();

        for (; i >= 0; i--) {

            QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();

           // Date date = sdf.parse("2020-03-08 00:00:00");
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());

            calendar.set(Calendar.DAY_OF_MONTH,1);
            calendar.add(Calendar.MONTH,-i);

            String datestr = simpleDateFormat.format(calendar.getTime());

            if(lastMonthOrderAmount.get(datestr) != null)
            {
                amountList.add(lastMonthOrderAmount.get(datestr));
                orderNumList.add(lastMonthOrderNum.get(datestr));
                timelist.add(datestr.substring(5,7));
            }
            else {


                starttime = sdf.parse(datestr + " 00:00:00");

                calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));

                String endtimestr = simpleDateFormat.format(calendar.getTime());

                endtime = sdf.parse(endtimestr + " 23:59:59");

                timelist.add(datestr.substring(5,7));

                queryWrapper.ge(starttime != null, "or_date", starttime);
                queryWrapper.le(endtime != null, "or_date", endtime);
                queryWrapper.eq("or_status",1);

              //  System.out.println("查询日期：" + datestr);

              //  System.out.println("查询日期结束：" + endtimestr);

                List<OrderInfo> orderInfos = this.orderInfoService.list(queryWrapper);
                float amount = 0;


                for (OrderInfo orderInfo : orderInfos) {
                    try {
                        amount += orderInfo.getOrAmount();
                    } catch (Exception e) {
                        //System.out.println(orderInfo.getOrId());
                    }
                }
                amountList.add(amount);
                orderNumList.add(orderInfos.size());
                if(i !=0) {
                    lastMonthOrderAmount.put(datestr, amount);
                    lastMonthOrderNum.put(datestr,orderInfos.size());
                }
            }

        }

        return new ChartData(amountList.size(),timelist,amountList,orderNumList);
    }

    @RequestMapping("getTodayData")
    public Map<String,Float> getTodayData() throws Exception {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Map<String,Float> resultdata = new HashMap<>();
        Date starttime;
        Date endtime;


        QueryWrapper<GroupInfo> queryWrapper = new QueryWrapper<>();


        String datestr = simpleDateFormat.format(new Date());

        starttime = sdf.parse(datestr + " 00:00:00");
        endtime = sdf.parse(datestr + " 23:59:59");

        queryWrapper.ge(starttime != null, "gp_reg_date", starttime);
        queryWrapper.le(endtime != null, "gp_reg_date", endtime);
        //queryWrapper.eq("or_status",1);

        List<GroupInfo> groupInfos = this.groupInfoService.list(queryWrapper);

        resultdata.put("newGroup", (float) groupInfos.size());

        QueryWrapper<OrderInfo> queryWrapperOrder = new QueryWrapper<>();
        queryWrapperOrder.ge(starttime != null, "or_date", starttime);
        queryWrapperOrder.le(endtime != null, "or_date", endtime);
        queryWrapperOrder.eq("or_status",1);

        List<OrderInfo> orderInfos = this.orderInfoService.list(queryWrapperOrder);

        float amount = 0;
        for (OrderInfo orderInfo : orderInfos) {
            try {
                amount += orderInfo.getOrAmount();
            } catch (Exception e) {
                //System.out.println(orderInfo.getOrId());
            }
        }

        resultdata.put("amount",amount);
        resultdata.put("num", (float) orderInfos.size());


        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());

        calendar.set(Calendar.DAY_OF_MONTH,1);
        calendar.add(Calendar.MONTH,0);

        datestr = simpleDateFormat.format(calendar.getTime());
        starttime = sdf.parse(datestr + " 00:00:00");

       // System.out.println("start time:" + datestr);
      //  System.out.println("end time:" + endtime);

        QueryWrapper<OrderInfo> queryWrapperMonth = new QueryWrapper<>();
        queryWrapperMonth.ge(starttime != null, "or_date", starttime);
        queryWrapperMonth.le(endtime != null, "or_date", endtime);
        queryWrapperMonth.eq("or_status",1);

        orderInfos = this.orderInfoService.list(queryWrapperMonth);
       // System.out.println("order size:" + orderInfos.size());

        amount = 0;
        for (OrderInfo orderInfo : orderInfos) {
            try {
                amount += orderInfo.getOrAmount();
            } catch (Exception e) {
                //System.out.println(orderInfo.getOrId());
            }
        }
        resultdata.put("monthamount",amount);
       // resultdata.put("monthorderList",orderInfos);

        return resultdata;

    }

    @RequestMapping("getMonthOrders")
    public Map<String,Float> getMonthOrders() throws Exception {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String datestr = simpleDateFormat.format(new Date());
        Date starttime;
        Date endtime;
       // starttime = sdf.parse(datestr + " 00:00:00");
        endtime = sdf.parse(datestr + " 23:59:59");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());

        calendar.set(Calendar.DAY_OF_MONTH,1);
        calendar.add(Calendar.MONTH,0);

        datestr = simpleDateFormat.format(calendar.getTime());
        starttime = sdf.parse(datestr + " 00:00:00");

        // System.out.println("start time:" + datestr);
        //  System.out.println("end time:" + endtime);

        QueryWrapper<OrderInfo> queryWrapperMonth = new QueryWrapper<>();
        queryWrapperMonth.ge(starttime != null, "or_date", starttime);
        queryWrapperMonth.le(endtime != null, "or_date", endtime);
        queryWrapperMonth.eq("or_status",1);

        List<OrderInfo> orderInfoList = this.orderInfoService.list(queryWrapperMonth);

        Map<String,Float> materialrank = new HashedMap();




        for(OrderInfo orderInfo:orderInfoList)
        {
            try
            {
                JSONObject orderinfo = new JSONObject(orderInfo.getOrText());


                 JSONArray proitemlist = orderinfo.getJSONArray("orderItemList");
                for(Object prod:proitemlist)
                {
                    JSONObject jsonObject = new JSONObject(prod);

                    String prod_name = (String) jsonObject.get("prod_name");

                    if(materialrank.containsKey(prod_name)) {
                        float curnum =  materialrank.get(prod_name);
                        curnum += Float.parseFloat((String) jsonObject.get("item_priceStr")) * (Integer) jsonObject.get("item_number");
                        materialrank.put(prod_name,curnum);
                    }
                    else {
                        float price = Float.parseFloat((String) jsonObject.get("item_priceStr")) * (Integer) jsonObject.get("item_number");
                        materialrank.put(prod_name,price);
                    }

                }
            }
            catch(Exception e)
            {

            }

        }
        return materialrank;
    }
    @RequestMapping("getToDayOrderData")
    public List<OrderInfo> getToDayOrderData() throws Exception {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date starttime;
        Date endtime;


        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();

        String datestr = simpleDateFormat.format(new Date());

        starttime = sdf.parse(datestr + " 00:00:00");
        endtime = sdf.parse(datestr + " 23:59:59");

        queryWrapper.ge(starttime != null, "or_date", starttime);
        queryWrapper.le(endtime != null, "or_date", endtime);
        queryWrapper.eq("or_status",1);

        List<OrderInfo> orderInfos = this.orderInfoService.list(queryWrapper);

        return orderInfos;
    }

    @RequestMapping("getOutPutOrderStatic")
    public DataGridView getOutPutOrderStatic(OrderInfoVo vo) throws Exception
    {
       // IPage<OrderInfo> page = new Page<>(vo.getPage(),vo.getLimit());
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
       // queryWrapper.like(StringUtils.isNotBlank(vo.getOrText()),"or_text",vo.getOrText());

        queryWrapper.eq("or_status",1);

        // queryWrapper.eq("or_id","18014398509481985");

        if(vo.getStartTime() == null)
        {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            String datestr = simpleDateFormat.format(new Date());
            vo.setStartTime(sdf.parse(datestr + " 00:00:00"));
            vo.setEndTime(sdf.parse(datestr + " 23:59:59"));

        }
        queryWrapper.ge(vo.getStartTime() != null,"or_date",vo.getStartTime());
        queryWrapper.le(vo.getEndTime() != null,"or_date",vo.getEndTime());

        queryWrapper.orderByDesc("or_date");


       // this.orderInfoService.page(page,queryWrapper);


        List<UserInfo> userInfos = this.userInfoService.list();
        Map<Integer,String> userAccount = userInfos.stream().collect(Collectors.toMap(UserInfo::getUrId, UserInfo::getUrPhonenumber));

        List<GroupInfo> groupInfos = this.groupInfoService.list();
        Map<Long,String> groupMap = groupInfos.stream().collect(Collectors.toMap(GroupInfo::getGpId, GroupInfo::getGpName));

        List<OrderInfo> list =  this.orderInfoService.list(queryWrapper);
       // List<OrderInfoVo> result = new ArrayList<>();

        if(vo.getOutputCenter() == null)
            return new DataGridView(0,new ArrayList<>());
        List<String> outputcenter = Arrays.asList(vo.getOutputCenter().split(","));

        Map<String,Map<String, OrderStaticVo>> outputData = new HashMap<>();

        Map<String,Float> outputTotalAmount = new HashMap<>();
        for(OrderInfo g1:list) {

            OrderInfoVo orderInfoVo = new OrderInfoVo();
            BeanUtils.copyProperties(g1, orderInfoVo);

            orderInfoVo.parseOrderInfo();

            if(outputcenter.indexOf(orderInfoVo.getOutputCenter()) >= 0) {

                Long urid = groupInfoService.getById(orderInfoVo.getGpId()).getUrId();
                orderInfoVo.setOrderAccount( userAccount.get(urid.intValue()));
                orderInfoVo.setOrderCompany(groupMap.get(orderInfoVo.getGpId().longValue()));
               // result.add(orderInfoVo);
                if(outputData.containsKey(orderInfoVo.getOutputCenter()))
                {
                    Map<String,OrderStaticVo> companydata = outputData.get(orderInfoVo.getOutputCenter());
                    String customer = orderInfoVo.getCustomer().split("#")[0];

                    float cur = outputTotalAmount.get(orderInfoVo.getOutputCenter());
                    cur += orderInfoVo.getAmount();

                    outputTotalAmount.put(orderInfoVo.getOutputCenter(),cur);

                    if(companydata.containsKey(customer))
                    {
                        float amount = companydata.get(customer).getAmount() + orderInfoVo.getAmount();
                        companydata.get(customer).setAmount(amount);
                    }
                    else
                    {
                        OrderStaticVo staticVo = new OrderStaticVo();
                        BeanUtils.copyProperties(orderInfoVo, staticVo);
                        companydata.put(customer,staticVo);

                    }
                }
                else
                {
                    OrderStaticVo staticVo = new OrderStaticVo();
                    BeanUtils.copyProperties(orderInfoVo, staticVo);

                    Map<String,OrderStaticVo> hashmap = new HashMap<>();

                    String customer = orderInfoVo.getCustomer().split("#")[0];
                    outputTotalAmount.put(orderInfoVo.getOutputCenter(),orderInfoVo.getAmount());
                    hashmap.put(customer,staticVo);
                    outputData.put(orderInfoVo.getOutputCenter(),hashmap);

                }
            }

        }

        List<OrderStaticVo> result = new ArrayList<>();


        for (String key : outputData.keySet()) {

           Map<String,OrderStaticVo> companyOrder = outputData.get(key);
            for (String key1 : companyOrder.keySet()) {

                companyOrder.get(key1).setRatio( companyOrder.get(key1).getAmount()/outputTotalAmount.get(key));
                result.add(companyOrder.get(key1));

            }

        }

        Collections.sort(result, new Comparator<OrderStaticVo>() {
            @Override
            public int compare(OrderStaticVo m1,OrderStaticVo m2)
            {
                if(m1.getOutputCenter().equals(m2.getOutputCenter()) == false)
                    return 0;
                if( m1.getAmount() == m2.getAmount() )
                    return 0;
                if( m1.getAmount() > m2.getAmount() )
                    return -1;
                else
                    return 1;

            }

        });

        return new DataGridView(result.size(),result);
    }
    public void openSqlSession(String databaseurl) throws Exception
    {

            PooledDataSource dataSource = getDateSource(databaseurl);

            if(sqlSessionFactoryBean == null) {
                ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
                Resource[] resources = resolver.getResources("classpath:/mapper/orderxml/*Mapper.xml");

                sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
                sqlSessionFactoryBean.setMapperLocations(resources);
                sqlSessionFactoryBean.setDataSource(dataSource);

                SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();

                sqlsession = sqlSessionFactory.openSession();
            }
            else
                sqlSessionFactoryBean.setDataSource(dataSource);



    }

    public PooledDataSource getDateSource(String databaseurl)
    {
        PooledDataSource dataSource = new PooledDataSource();
        dataSource.setDriver("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/scfy?serverTimezone=UTC&useUnicode=true&useSSL=false&characterEncoding=utf8");
        dataSource.setUsername("root");
        dataSource.setPassword("11223344");

        return dataSource;
    }


}

